package com.fable.sp.core.widget;

import freemarker.template.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;

/**
 * .
 *
 * @author stormning on 16/8/16.
 */
public class WidgetRequestHashModel implements TemplateHashModelEx, Serializable {

    private final ObjectWrapper wrapper;
    private final WidgetRequest request;

    public WidgetRequestHashModel(WidgetRequest request, ObjectWrapper wrapper) {
        this.request = request;
        this.wrapper = wrapper;
    }

    @Override
    public TemplateModel get(String key) throws TemplateModelException {
        return wrapper.wrap(request.getAttribute(key));
    }

    @Override
    public boolean isEmpty() throws TemplateModelException {
        return !request.getAttributeNames().hasMoreElements();
    }


    @Override
    public int size() throws TemplateModelException {
        int result = 0;
        for (Enumeration enumeration = request.getAttributeNames(); enumeration.hasMoreElements(); ) {
            enumeration.nextElement();
            ++result;
        }
        return result;
    }

    @Override
    public TemplateCollectionModel keys() throws TemplateModelException {
        ArrayList keys = new ArrayList();
        for (Enumeration enumeration = request.getAttributeNames(); enumeration.hasMoreElements(); ) {
            keys.add(enumeration.nextElement());
        }
        return new SimpleCollection(keys.iterator());
    }

    @Override
    public TemplateCollectionModel values() throws TemplateModelException {
        ArrayList values = new ArrayList();
        for (Enumeration enumeration = request.getAttributeNames(); enumeration.hasMoreElements(); ) {
            values.add(request.getAttribute((String) enumeration.nextElement()));
        }
        return new SimpleCollection(values.iterator(), wrapper);
    }
}
